package com.acwing.lc.part1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author rkc
 * @date 2022/9/10 9:41
 */
public class LC18四数之和 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                for (int l = j + 1, r = nums.length - 1; l < r; l++) {
                    if (l > j + 1 && nums[l] == nums[l - 1]) continue;
                    while (l < r - 1 && nums[i] + nums[j] + nums[l] + nums[r - 1] >= target) r--;
                    if ((long) (nums[i] + nums[j]) + (long) (nums[l] + nums[r]) == target) {
                        ans.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                    }
                }
            }
        }
        return ans;
    }
}
